<template>
  <div class="about">
     <!--搜索-->
        <el-row>
            <el-col :span="6"><el-input v-model="userName" size="mini" placeholder="请输入用户名"></el-input></el-col>
            <el-col :span="6"><el-input v-model="email" size="mini" placeholder="请输入邮箱"></el-input></el-col>
            <el-col :span="6"><el-input v-model="phonenumber" size="mini" placeholder="请输入手机号"></el-input></el-col>
            <el-col :span="6"><el-button type="primary" @click="search"  size="mini" icon="el-icon-search">搜索</el-button>
            &nbsp;<el-button type="primary"  size="mini" icon="el-icon-circle-plus" @click="handleAdd">添加</el-button>
            <el-button type="primary" size="mini" @click="flush()" icon="el-icon-search">刷新</el-button></el-col>
            <el-col :span="6"><div class="grid-content bg-purple-light">&nbsp;</div></el-col>
        </el-row>
        <!--分页列表显示-->
        <el-row>
            <el-table
                :data="tableData"
                style="width: 100%">
                <el-table-column type="index" label="#" sortable> </el-table-column>
                <el-table-column width="100px" prop="userName" label="用户名"></el-table-column>
                <el-table-column prop="loginName" label="登录昵称"></el-table-column>          
                <el-table-column prop="userType" :formatter="getTypeName" label="用户类型"></el-table-column>
                <el-table-column width="160px" prop="email" label="用户邮箱"></el-table-column>
                <el-table-column width="150px" prop="phonenumber" label="手机号码"></el-table-column>
                <el-table-column prop="sex" :formatter="getSexName" label="用户性别"></el-table-column>
                <el-table-column label="头像">
                        <template slot-scope="scope">
                            <el-image
                                    style="width: 50px; height: 50px"
                                    :src="scope.row.avatar"
                                     ></el-image>
                        </template>      
                </el-table-column>
                <el-table-column :formatter="getStatusName" prop="status" label="状态"></el-table-column>                           
                <!-- <el-table-column width="150px" prop="loginIp" label="最后登陆IP"></el-table-column> -->
                <!-- <el-table-column width="175px" label="最后一次登录时间">
                    <template slot-scope="scope">
                        <i class="el-icon-time"></i>
                        <span style="margin-left: 10px">{{ scope.row.loginDate | dateFilter("yyyy-mm-dd hh:mm:ss")  }}</span>
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" width="270">
                    <template slot-scope="scope">
                        <el-button
                                type="primary"
                                size="mini"
                                @click="toShowRoles(scope.$index, scope.row)">赋予角色</el-button>
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row,)">编辑</el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!--分页插件-->
        <el-row>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[2,3,5,10,100, 200, 300, 400]"
                    :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-row>
        <!--添加和更新 弹框-->
        <el-row>
            <el-dialog :title="title" :visible.sync="dialogFormVisible">
                <el-form :model="form" :rules="rules" ref="form" label-position="left">
                    <el-form-item label="头像上传" >
                        <!--图片上传-->
                        <el-upload
                                class="avatar-uploader"
                                :action="url"
                                name="file"
                                :auto-upload='true'
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img style="width: 100px; height: 100px" v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="登录昵称" prop="loginName" :rules="rules.loginName" >
                        <el-input v-model="form.loginName" auto-complete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="用户名" prop="userName" :rules="rules.userName" >
                        <el-input v-model="form.userName" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户类型" prop="userType" >
                        <el-radio-group v-model="form.userType">
                            <el-radio v-model="form.userType" label="0">管理员</el-radio>
                            <el-radio v-model="form.userType" label="1">代理商</el-radio>
                            <el-radio v-model="form.userType" label="2">商户</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="用户邮箱" prop="email" :rules="rules.email" >
                        <el-input v-model="form.email" auto-complete="off"></el-input>                 
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phonenumber" :rules="rules.phonenumber" >
                        <el-input v-model.number="form.phonenumber" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户性别" prop="sex" >
                        <el-radio-group v-model="form.sex">
                            <el-radio v-model="form.sex" label="0">男</el-radio>
                            <el-radio v-model="form.sex" label="1">女</el-radio>
                            <el-radio v-model="form.sex" label="2">未知</el-radio>
                        </el-radio-group> 
                    </el-form-item>
                    
                    <el-form-item label="帐号状态" prop="status" >
                       <el-radio-group v-model="form.status"> 
                            <el-radio v-model="form.status" label="0">正常</el-radio>
                            <el-radio v-model="form.status" label="1">停用</el-radio>
                        </el-radio-group>                  
                    </el-form-item>
                    <!-- <el-form-item label="最后登陆时间" >
                        <el-date-picker
                        v-model="form.loginDate"
                        type="datetime"
                        placeholder="选择日期时间"
                        align="right"
                        :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item> -->
                    <el-form-item label="密码" prop="password" >
                        <el-input :placeholder="form.password" v-model="form.password" autocomplete="off" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="repassword" >
                        <el-input :placeholder="form.repassword" v-model="form.repassword" autocomplete="off" show-password></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addOrUpdate('form')">确 定</el-button>
                </div>
            </el-dialog>
        


             <!--角色授权弹出框-->
            <el-dialog title="角色列表" :visible.sync="rolesVisible">
                <template>
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
                        <el-checkbox v-for="role in roles" :label="role.role_id" :key="role.role_id">{{role.role_name}}</el-checkbox>
                    </el-checkbox-group>
                </template>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="addUserAndRole()">确 定</el-button>
                </div>
            </el-dialog>
        </el-row>
        <!--修改-->
        <el-row>
            <el-dialog :title="title" :visible.sync="dialogFormVisible1">
                <el-form :model="form1" :rules="rules" ref="form1" label-position="left">
                    <el-form-item label="头像上传" >
                        <!--图片上传-->
                        <el-upload
                                class="avatar-uploader"
                                :action="url"
                                name="file"
                                :auto-upload='true'
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img style="width: 100px; height: 100px" v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="登录昵称" prop="loginName" :rules="rules.loginName" >
                        <el-input v-model="form1.loginName" auto-complete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="用户名" prop="userName" :rules="rules.userName" >
                        <el-input v-model="form1.userName" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户类型" prop="userType" >
                        <el-radio-group v-model="form1.userType">
                            <el-radio v-model="form1.userType" label="0">管理员</el-radio>
                            <el-radio v-model="form1.userType" label="1">代理商</el-radio>
                            <el-radio v-model="form1.userType" label="2">商户</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="用户邮箱" prop="email" :rules="rules.email" >
                        <el-input v-model="form1.email" auto-complete="off"></el-input>                 
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phonenumber" :rules="rules.phonenumber" >
                        <el-input v-model.number="form1.phonenumber" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户性别" prop="sex" >
                        <el-radio-group v-model="form1.sex">
                            <el-radio v-model="form1.sex" label="0">男</el-radio>
                            <el-radio v-model="form1.sex" label="1">女</el-radio>
                            <el-radio v-model="form1.sex" label="2">未知</el-radio>
                        </el-radio-group> 
                    </el-form-item>
                    
                    <el-form-item label="帐号状态" prop="status" >
                       <el-radio-group v-model="form1.status"> 
                            <el-radio v-model="form1.status" label="0">正常</el-radio>
                            <el-radio v-model="form1.status" label="1">停用</el-radio>
                        </el-radio-group>                  
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible1 = false">取 消</el-button>
                    <el-button type="primary" @click="addOrUpdate('form1')">确 定</el-button>
                </div>
            </el-dialog>
        </el-row>
  </div>
</template>
<script>
export default {
      data() {
        var checkPhone = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('手机号不能为空'));
        } else {
          const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
          console.log(reg.test(value));
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error('请输入正确的手机号'));
            }
          }
        };
        var validatePass2 = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请再次输入密码'))
        } else if (value !== this.form.password) {
            callback(new Error('两次输入密码不一致!'))
        } else {
            callback()
          }
        };
        return {
            url:this.$base_url+"/api/cs/commonOSS/upload?accessToken="+localStorage.getItem("token"),
               tableData:[],
                currentPage:1,//当前页面，默认1
                pageSize:5,//每页显示条数
                total:100,//分页总数量，默认值随便写，初始化时赋予新值
                userName:'',//查询功能
                email:'',
                phonenumber:'',
                dialogFormVisible:false,
                dialogFormVisible1:false,
                title:'用户添加',
                
                form:{
                    // loginName:'',
                    // userName:'',
                    // radio:'',
                    // email:'',
                    // phonenumber:'',
                    // userType:'',
                    // sex:'',
                    // status:'',
                   
                },
                addForm:{
                    // loginName:'',
                    // userName:'',
                    // radio:'',
                    // email:'',
                    // phonenumber:'',
                    // userType:'',
                    // sex:'',
                    // status:'',
                },
                form1:{
                    // loginName:'',
                    // userName:'',
                    // radio:'',
                    // email:'',
                    // phonenumber:'',
                    // userType:'',
                    // sex:'',
                    // status:'',
                },
                rules:{
                    loginName:[
                        {required: true, trigger: ["blur", "change"], message: "请输入登录昵称" },
                        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }  
                    ],
                    userName:[
                        {required: true, trigger: ["blur", "change"], message: "请输入用户名" },
                        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ],
                    email:[
                         {required: true, trigger: ["blur", "change"], message: "请输入邮箱地址" },
                         { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
                     ],
                    phonenumber:[
                         {validator: checkPhone, trigger: 'blur'},  
                     ],
                    userType:[
                        {required: true, message: '请选择用户类型', trigger: 'change' }
                     ],
                    sex:[
                        {required: true, message: '请选择用户性别', trigger: 'change' }
                    ],
                    status:[
                        {required: true, message: '请选择用户状态', trigger: 'change' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,30}$/, message: '密码为数字，小写字母，大写字母，特殊符号 至少包含三种，长度为 8 - 30位，密码不能包含 用户名，公司名称(lidian), 公司域名(rekoon) （判断的时候不区分大小写)' }
                    ],
                    repassword: [
                        { required: true, validator: validatePass2, trigger: 'blur' }
                    ],
                   

                },
                radio:'1',
                roleId:0,//角色id
                loginName:'',
                userName:'',
                email:'',
                phoneNumber:'',
                rolesVisible:false,//角色列表弹出框
                //用户关联角色相关的
                checkAll: false,
                checkedRoles: [],
                roles: [],
                isIndeterminate: true,
                roleIds:'',
                userId:0,
                imageUrl:'',
                pickerOptions:{
                    shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                    picker.$emit('pick', new Date());
                    }
                    }, {
                    text: '昨天',
                    onClick(picker) {
                    const date = new Date();
                    date.setTime(date.getTime() - 3600 * 1000 * 24);
                    picker.$emit('pick', date);
                    }
                    }, {
                    text: '一周前',
                    onClick(picker) {
                    const date = new Date();
                    date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', date);
                    }
                }]
            },
             value1: '',
             value2: '',
        };
      },
      
       created:function(){
            var _this =this;
            _this =this;
                 //初始化数据，加载所有的角色
                 this.$http.get('/api/cs/role/page',{
                     params: {
                             pageNo:1,
                             pageSize:1000,
                             
                     }
                 }).then(function (response) {
                         _this.roles=response.data.data.page;
                         //console.log(_this.roles);
                     });
               //初始化
            this.loadData();
            },
            
            methods:{
                //加载数据
                loadData(){
                   //动态菜单请求
                          this.$http.post("/api/cs/user/queryAll?pageNo="+this.currentPage+"&pageSize="+this.pageSize,{
                                            userName:this.userName,
                                            phonenumber:this.phonenumber,
                                            email:this.email
                                      }).then((response) => {
                                                 console.log(response);
                                              if(response.data.code==2000){
                                                  this.tableData = response.data.data.list;
                                                  this.total = response.data.data.total;
                                              }
                                })
                    
                },
                //各种绑定事件方法
                //每页数量发生变化
                handleSizeChange(val) {
                    console.log(`每页 ${val} 条`);
                    this.pageSize=val;
                    this.loadData();
                },
                //当前页发生变化
                handleCurrentChange(val) {
                    console.log(`当前页: ${val}`);
                    this.currentPage=val;
                    this.loadData();
                },
                //用户类型获取名称
                getTypeName(row, column, cellValue) {
                    // return cellValue==0?'后台管理员':cellValue==1?"代理商":"商户";
                    var tmpType = '';
                    if (cellValue == 0) {
                        tmpType = '管理员';
                    } else if (cellValue == 1) {
                        tmpType = '代理商';
                    } else {
                        tmpType = '商户';
                    }
                    return tmpType;
                },
                //用户性别
                getSexName(row, column, cellValue) {
                return cellValue == 0 ? '男' : cellValue == 1 ? '女' : '未知';
                },
                /* var tmpType = "";
                     if (cellValue == 0) {
                         tmpType = "后台管理员";
                     } else if (cellValue == 1) {
                         tmpType = "代理商";
                     } else {
                         tmpType = "商户";
                     }
                     return tmpType;*/
                //账户状态名字
                getStatusName(row, column, cellValue) {
                    return cellValue == 0 ? '正常' : '禁用';
                },
                //查询方法
                search(){
                   this.loadData();
                },
                //处理添加
                handleAdd(){
                    //清空原来form
                    this.form={};
                    this.imageUrl='';
                    //更新显示名称
                    this.title="用户添加";
                    //对话框显示
                    this.dialogFormVisible=true;
                    this.$refs.form.resetFields();
                },
                //处理编辑（弹出部门更新对话框）
                handleEdit(index, row) {
                    console.log(index, row);
                    this.form1 =  JSON.parse(JSON.stringify( row));
                    this.imageUrl=row.avatar;
                    console.log(row)
                    //更新显示名称
                    this.title="用户更新";
                    //对话框显示
                    this.dialogFormVisible1=true;
                },
                //提交表单数据（添加或者更新）
                addOrUpdate(formName){
                    var _this = this;
                    var  url ='/api/cs/user/update';
                    this.addForm=this.form1;
                    if( this.addForm.userId==''||this.addForm.userId==null){
                        url="/api/cs/user/insert"
                    this.addForm={};
                        this.addForm=this.form;
                    }
                    // alert(JSON.stringify(this.addForm))
                    _this=this;
                    this.$refs[formName].validate(bool => {
                    if (bool) {
                         //提交方法
                        //  alert(JSON.stringify(this.addForm.avatar))
                    this.$http.post(url,this.addForm)
                        .then(function (response) {
                            console.log(response);
                            //提交成功
                            if(response.data.code==2000){
                                //关闭弹出框
                                _this.dialogFormVisible=false;
                                _this.dialogFormVisible1=false;
                                //提示更新成功
                                _this.$message({
                                  //  message: '恭喜你，这是一条成功消息',
                                    message: response.data.message,
                                    type: 'success'
                                });
                                //重新加载数据
                                _this.loadData();
                            }else {
                                _this.$message.error(response.data.message);
                            }
                        })
                        .catch(function (error) {
                            _this.$message.error('错了哦，这是一条错误消息');
                        });

                     }else{
                        console.log('error submit!!');
                         return false;
                     }
                }); 
                },
                flush(){
                     //this.loadData()
                    location.reload();
                 },
                 
                //图片上传成功后
                 handleAvatarSuccess:function(res, file) {
                     //图片回显
                     this.imageUrl = URL.createObjectURL(file.raw);
                  //   alert(file.response);
                    // alert(JSON.stringify(file.response));
                    // alert(JSON.stringify(res))
                    // alert(JSON.stringify(file))
                    // alert(res.ossFileUrlBoot)
                    this.form1.avatar=res.ossFileUrlBoot;
                     this.form.avatar=file.response.ossFileUrlBoot;
                     // this.form.fileName=file.response.oldFileName;
                     // this.form.filePath=file.response.newFilePath;
                 },
                 //上传前图片类型和大小判断
                 beforeAvatarUpload:function(file) {
                     // const isJPG = file.type === 'image/jpeg';
                     const isLt2M = file.size / 1024 / 1024 < 2;

                     /* if (!isJPG) {
                          this.$message.error('上传头像图片只能是 JPG 格式!');
                      }*/
                     if (!isLt2M) {
                         this.$message.error('上传头像图片大小不能超过 2MB!');
                     }
                     return  isLt2M;
                 },
                 //弹出角色选择对话框
                 toShowRoles:function (index,row){
                     var _this =this;
                     this.userId=row.userId;
                     //console.log(this.userId);
                     //根据当前用户ID查询对应的所有角色id集合 赋值给默认选中checkedRoles
                     _this =this;
                     //初始化数据，加载所有的角色
                     this.$http.get('/api/cs/user/listRoleIdsByUserId?userId='+row.userId).then(function (response) {
                         _this.checkedRoles=response.data.data;
                     });

                      this.rolesVisible=true;
                 },
                 //添加用户和角色关联方法
                 addUserAndRole(){
                     var _this =this;
                     _this =this;
                     console.log("roleIds:"+this.roleIds);
                     if(this.roleIds.length<1){
                         _this.$message.error("至少选中一个角色。。。");
                         return;
                     }
                     //调用后台方法，添加数据库
                     //console.log(this.userId);
                     this.$http.post('/api/cs/user/addUserAndRole?userId='+this.userId+"&roleIds="+this.roleIds).then(function (response) {
                         console.log(response);
                         if(response.status == 200){
                             if(response.data.data>0) {
                                 //提示成功
                                 _this.$message({
                                     type: 'success',
                                     message: '添加成功!'
                                 });
                                 //关闭弹框
                                 _this.rolesVisible=false;
                                 //重新加载数据
                                 _this.loadData();
                             }
                         }
                     }).catch(function (error) {
                         console.log(error);
                         _this.$message.error("你错了。。。");
                     });
                 },
                 //处理全选改变
                  handleCheckAllChange(val) {
                     //console.log("。。。。"+val);
                     if(val) {//判断是否为true
                         for (var i = 0; i < this.roles.length; i++) {
                             this.checkedRoles.push(this.roles[i].roleId);
                         }
                     }else{
                         this.checkedRoles=[];
                     }
                     //this.checkedRoles = val ? this.roles : [];
                     this.isIndeterminate = false;
                 },
                 handleCheckedRolesChange(value) {
                     console.log("选中的："+value);
                     this.roleIds=value;
                     let checkedCount = value.length;

//                     console.log("双等："+('1'==1));//true
//                     console.log("三个等："+('1'===1));//false
//                     console.log("三个等："+('1'==='1'));//true
//                     console.log("三个等："+(1===1));//true
                     this.checkAll = checkedCount === this.roles.length; //=== 数据类和数据都要匹配
                                                                           //== 数据匹配
                     this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
                 },
                 
                //处理删除（ 部门删除）
                handleDelete(index, row) {
                    var _this = this;
                    console.log(index, row);
                    _this=this;
                    //确认弹框
                    this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        //执行删除
                       this.$http.delete('/api/cs/user/deleteById?userId='+row.userId)
                            .then(function (response) {
                                //判断删除是否成功
                                 if(response.data.code==2000){
                                     //提示
                                     _this.$message({
                                         type: 'success',
                                         message: '删除成功!'
                                     });
                                     //重新加载数据
                                     _this.loadData();
                                 }else {
                                     _this.$message.error(response.data.message);
                                 }
                            })
                            .catch(function (error) {
                                //失败处理
                                console.log(error);
                                _this.$message.error('删除失败!');
                            });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });


                }
            },filters: {
                    //时间格式处理
                    dateFilter: function (data, format = "") {
                        var dt = new Date(data);
                        var y = dt.getFullYear();
                        var m = (dt.getMonth()+1).toString().padStart(2,"0");
                        var d = dt.getDate().toString().padStart(2,"0");
                        var h = dt.getHours().toString().padStart(2,"0");
                        var mm = dt.getMinutes().toString().padStart(2,"0");
                        var s = dt.getSeconds().toString().padStart(2,"0");
                        if (format.toLocaleLowerCase() === "yyyy-mm-dd" ||
                            format.toLocaleLowerCase() === "") {
                            return `${y}-${m}-${d}`;
                        } else if (format.toLocaleLowerCase() === "yyyy/mm/dd") {
                            return `${y}/${m}/${d}`;
                        } else if (format.toLocaleLowerCase() === "yyyy-mm-dd hh:mm:ss") {
                            return `${y}-${m}-${d} ${h}:${mm}:${s}`;
                        } else if (format.toLocaleLowerCase() === "yyyy/mm/dd hh:mm:ss") {
                            return `${y}/${m}/${d} ${h}:${mm}:${s}`;
                        } else {
                            return `输入的时间格式有误`;
                        }
                    },
                },
    }
</script>
<style>

</style>

